var express = require('express');
var router = express.Router();
const bodyParser = require('body-parser');
const getConfig = require('../controller/getConfig');
const controllerBlock = require('../controller/block');
const blockSaveImage = require('../controller/upload');
const { engine } = require('../util/liquid');
const storeController = require('@app/controller/store');
// const { fsExistsSync } = require('@app/util/index');
const themeConfig = require('@app/config/theme');
const {
  getThemeAll,
  getThemeSections,
  createTemplate,
} = require('@app/service/section');
const { compilerTailwindcss } = require('../../util/tailwindcss');
const multer = require('multer');
const { globalCache } = require('../util/memoryCache');

// 配置Multer中间件处理文件上传
const upload = multer({ limits: { fieldSize: 100 * 1024 * 1024 } });

// var { compilerStyle } = require('../../config/src/style');

// 渲染积木块
router.post('/render/:temp/block/:block', bodyParser.json(), function (req, res) {
  var blockFile = `./src/theme/${req.params.temp}/sections/${req.params.block}.liquid`;
  themeConfig.setThemeName(req.params.temp);
  const html = engine.renderFileSync(blockFile, {
    section: req.body.default,
  });
  compilerTailwindcss(html).then(css=>console.log(css));
  // let resultCss = "";

  // if (fsExistsSync(`./src/theme/${req.params.temp}/lib/style/modules/${req.params.block}.scss`)) {
  //     resultCss += sass.compileString(readFile(`./src/theme/${req.params.temp}/lib/style/app.scss`).replace(/@import.*;/g,'')).css;
  //     resultCss += sass.compile(`./src/theme/${req.params.temp}/lib/style/modules/${req.params.block}.scss`).css;
  //     // .replace(/@import.*;/g,'')
  //     // console.log(readFile(`./src/theme/${req.params.temp}/lib/style/app.scss`));
  // }

  res.send({
    code: 200,
    data: {
      // link: `http://localhost:3030/theme/${req.params.temp}/assets/${req.params.temp}_theme.css`,
      // css:result.css,
      html: html,
    },
    msg: '成功',
  });
  // res.send(`<link rel="stylesheet" type="text/css" href="http://localhost:3030/theme/${req.params.temp}/assets/${req.params.temp}_theme.css">` + html);
  return;
  // if (fsExistsSync(`./src/theme/${req.params.temp}/lib/style/app.scss`)) {
  //   compilerStyle(
  //     {
  //       from: `./src/theme/${req.params.temp}/lib/style/app.scss`,
  //       to: '',
  //     },
  //     req.params.temp,
  //     false,
  //     function (css) {
  //       res.send(`<style>${css}</style>` + html);
  //     }
  //   );
  // } else {
  //   // const css = readFile(`./src/theme/${req.params.temp}/assets/${req.params.temp}_theme.css`)
  //   res.send(
  //     `<link rel="stylesheet" type="text/css" href="http://localhost:3030/theme/${req.params.temp}/assets/${req.params.temp}_theme.css">` +
  //               html
  //   );
  // }
});


// 获取模版全局配置
router.get('/globalConfig/:id', bodyParser.json(), controllerBlock.getGlobalConfig);
// 获取积木块的配置
router.get('/sections/config', bodyParser.json(), controllerBlock.getSectionsConfig);
// 图片上传
router.post('/upload', upload.single('additionalFile'), blockSaveImage);

router.get('/template/all', bodyParser.json(), function (req, res) {
  res.json({ data: getThemeAll() }).end();
});

router.get('/template/sections/all', bodyParser.json(), function (req, res) {
  res.json({ data: getThemeSections(req.query.name) }).end();
});

// 创建模版
router.post('/create/template', bodyParser.json(), async (req, res) => {
  const css = await createTemplate(req.body);
  res.json({ data: css }).end();
});

// 更新积木块信息
router.post('/block', bodyParser.json(), function (req, res) {
  controllerBlock.addBlock(req.body);
  res.json({ code: 200, data: '', msg: '添加成功' }).end();
});

// 获取积木块信息
router.get('/block', bodyParser.json(), function (req, res) {
  res.json({ code: 200, data: controllerBlock.getBlocks(req.query), msg: '添加成功' }).end();
});

// 删除积木块
router.delete('/block', bodyParser.json(), function (req, res) {
  controllerBlock.delBlock(req.body);
  res.json({ code: 200, data: '', msg: '删除成功' }).end();
});

//更新积木块信息
router.put('/block', bodyParser.json(), function (req, res) {
  controllerBlock.updateBlock(req.body);
  res.json({ code: 200, data: '', msg: '更新成功' }).end();
});

router.put('/blockAll', bodyParser.json(), function (req, res) {
  controllerBlock.updateBlockAll(req.body);
  res.json({ code: 200, data: '', msg: '更新成功' }).end();
});

router.post('/addBlock', bodyParser.json(), function (req, res) {
  controllerBlock.addBlock(req.body);
  res.json({ code: 200, data: '', msg: '添加成功' }).end();
});

// 渲染积木块
router.get('/block/allConfig', bodyParser.json(), function (req, res) {
  const data = getConfig();
  res.json({ data: data }).end();
});

// 获取所有模版积木块配置
router.get('/themeAll', bodyParser.json(), function (req, res) {
  res.json({ data: controllerBlock.getThemeAllAndSections() }).end();
});

// 获取所有模版积木块配置
router.get('/cardAll', bodyParser.json(), function (req, res) {
  res.json({ data: controllerBlock.getCardAll() }).end();
});

// 获取所有模版积木块配置
router.post(
  '/homeapi/:id/one-page-checkouts/:id/paymentform',
  bodyParser.json(),
  function (req, res) {
    res.json({ code: 0, data: controllerBlock.paymentform() }).end();
  }
);

// 支付列表
router.post('/:id/one-page-checkouts/:id/payments', bodyParser.json(), function (req, res) {
  res.json({
    code: 0,
    data: {
      payment_list: [
        // {
        //     "id": 15267,
        //     "payment_name": "paypal自填",
        //     "interface_type": "paypal21",
        //     "interface_type_param": {
        //         "account": "231241242@qq.com",
        //         "client_id": "AZn1ZkOp2yz1fk_Jq_iUkZs9pGlyoZmh12KL6w0OgXhu97X2OgXlo3lyVMB8Rd3D5yfQp1H-ZD2S4M75",
        //         "secret": "EIRj5pufME0qz1NLiUf4PZvY2oJqq2Xp7jy6EeoADKlaz2WMiYm1r1DLejn_rd1ppmUsLz0DBgm9c0pN",
        //         "smart_button": 1,
        //         "tracking_status": 1,
        //         "express_checkout": 1,
        //         "api_is_test": 1,
        //         "webhook_url": "https://{yourdomain}/homeapi/checkouts/server/paypal21/callback",
        //         "authorize_payment": 0,
        //         "authorize_auto_capture": 0,
        //         "authorize_auto_capture_time": 0,
        //         "authorize_auto_time_type": "hour",
        //         "authorize_auto_time_start": 1,
        //         "authorize_auto_time_end": 2,
        //         "is_auto_submit": 1,
        //         "b_domain": "https://hanpeng.oemsaas.cn",
        //         "brand_name": "这个是品牌名称",
        //         "lexicon": "这个是小鱼的词库,这个是韩鹏的词库,hellow",
        //         "type": 4,
        //         "button_src": ""
        //     },
        //     "image": "https://imgcdn.oemsaas.shop/statics/cart/payment/paypal.png",
        //     "price": 0,
        //     "original_price": 0,
        //     "descript": "PayPal自填中",
        //     "reception_descript": "PayPal自填中",
        //     "is_redirect": false,
        //     "accepted_payment_brand": [
        //         "visa",
        //         "mastercard",
        //         "american_express",
        //         "apple_pay"
        //     ],
        //     "payment_kind_type": "three_nested_paypal",
        //     "position": 999999999,
        //     "button_src": "",
        //     "preloading_html": ""
        // },
        {
          id: 16506,
          payment_name: 'Stripe（信用卡）',
          interface_type: 'stripecard',
          interface_type_param: {
            key: 'pk_test_51JxSjyBLtdJcW0qwaGGciYxEVS1K9ysJvm01fRDCpDQGKeUpAJ7RWa7h007sdzxXMK2F0ug05HaCkC4MMXPMRR8J00Zn5yHqF4',
            secret: 'sk_test_51JxSjyBLtdJcW0qwf0tHsp2LYYMxWlZ0BxOOHGE1e0Xgp8izS3tYY1VoNXCAxKQelmtZq5CUlp9Q8e9cGbRrLD1J00yR1QTo53',
            account: '1449407849@qq.com',
            tracking_status: 1,
            webhook_url: '',
            type: 4,
          },
          image: 'https://imgcdn.oemsaas.shop/statics/cart/payment/stripe.png',
          price: 0,
          original_price: 0,
          descript: '',
          reception_descript: '',
          is_redirect: false,
          accepted_payment_brand: ['mastercard'],
          payment_kind_type: 'reset_three_sdk_button',
          position: 999,
          button_src: '',
          preloading_html: '',
        },
      ],
    },
  }).end();
});

router.post('/checkouts/:id/payment', bodyParser.json(), function (req, res) {
  res.json({ code: 0, data: {} }).end();
});

// ============= 缓存相关接口 (遵循RESTful规范) =============
// POST /api/cache/store - 存储对象到缓存
router.post('/cache/store', bodyParser.json(), storeController.cacheStore);

// GET /api/cache/get/:key - 获取缓存对象
router.get('/cache/get/:key', storeController.cacheGet);

// DELETE /api/cache/delete/:key - 删除缓存
router.delete('/cache/delete/:key', storeController.cacheDelete);

// DELETE /api/cache/clear - 清空所有缓存
router.delete('/cache/clear', storeController.cacheClear);

// GET /api/cache/info - 获取缓存信息
router.get('/cache/info', storeController.cacheInfo);

// POST /api/cache/batch-store - 批量存储缓存
router.post('/cache/batch-store', bodyParser.json(), storeController.cacheBatchStore);

// ============= Lang 配置相关接口 =============
// POST /api/lang/store - 设置语言配置
router.post('/lang/store', bodyParser.json(), storeController.langStore);

// GET /api/lang/get - 获取语言配置
router.get('/lang/get', storeController.langGet);

// ============= 代理配置相关接口 =============
// POST /api/proxy/domain - 设置代理目标域名
router.post('/proxy/domain', bodyParser.json(), (req, res) => {
  const { domain } = req.body;
  if (!domain) {
    return res.status(400).json({
      success: false,
      message: '域名不能为空',
    });
  }

  try {
    globalCache.set('global_current_domain', domain);
    console.log('更新代理目标域名:', domain);
    res.json({
      success: true,
      message: '代理域名设置成功',
      domain: domain,
    });
  } catch (error) {
    console.error('设置代理域名失败:', error);
    res.status(500).json({
      success: false,
      message: '设置代理域名失败',
      error: error.message,
    });
  }
});

// GET /api/proxy/domain - 获取当前代理目标域名
router.get('/proxy/domain', (req, res) => {
  const currentDomain = globalCache.get('global_current_domain');
  res.json({
    success: true,
    domain: currentDomain,
    hasDomain: !!currentDomain,
  });
});

// GET /api/proxy/test - 测试代理配置
router.get('/proxy/test', async (req, res) => {
  try {
    const currentDomain = globalCache.get('global_current_domain');

    res.json({
      success: true,
      message: '代理配置测试',
      data: {
        currentDomain: currentDomain,
        hasDomain: !!currentDomain,
        defaultDomain: process.env.DEFAULT_DOMAIN || 'http://localhost:8080',
        timestamp: new Date().toISOString(),
      },
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '测试失败',
      error: error.message,
    });
  }
});

module.exports = router;
